package com.ljkj.cordial.chat.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.PhotoHorizontalAdapter;
import com.ljkj.cordial.chat.base.BaseActivity;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.widget.CircleProgressBar;
import com.nic.view.util.glide.GlideUtil;
import com.nic.view.widget.ZoomImageView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MulPhotoPreviewActivity extends BaseActivity {
    public final static String IMG = "img";
    public final static String LIST = "list";
    private ViewPager viewPager;
    private ViewAdapter adapter;

    private ImageView ivBack;
    //    private String targetId;
    private String targetSelectedId;
    private List<ChatTableBean> picList = new ArrayList<>();
    private RecyclerView recyclerView;
    private PhotoHorizontalAdapter horizontalAdapter;
    private Map<Long, Boolean> loadMap = new HashMap<>();


    @Override
    public int getContentLayoutId() {
        return R.layout.activity_mul_photo_preview;
    }

    @Override
    public void initView() {
        setToolbarVisibility(View.GONE);
//        targetId = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_ID);
        targetSelectedId = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_SELECTED_ID);
        List<ChatTableBean> list = (List<ChatTableBean>) getIntent().getSerializableExtra(Canstants.KEY_CHAT_LIST);
        recyclerView = findViewById(R.id.recycle_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        horizontalAdapter = new PhotoHorizontalAdapter();
        recyclerView.setAdapter(horizontalAdapter);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        adapter = new ViewAdapter();
        viewPager.setAdapter(adapter);
//        viewPager.setOffscreenPageLimit(30);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                try {
                    View view = adapter.getDatas().get(position);
                    ViewHolder viewHolder = new ViewHolder(view);
                    ChatTableBean chat = picList.get(position);
                    refreshItemView(viewHolder, chat);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        getChatList(list);
    }


    @NonNull
    private View getZoomImageView(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.view_mul_photo, null,false);
        String path = picList.get(position).getThumbPath();
        ViewHolder viewHolder = new ViewHolder(view);
        viewHolder.zoomImageView.setImageBitmap(BitmapFactory.decodeFile(path));
        return view;
//        FrameLayout frameLayout = new FrameLayout(this);
//        frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//
//        CircleProgressBar progressBar = new CircleProgressBar(this);
//        int progressSize = CircleProgressBar.dpToPx(38, this);
//        int progressMargin = CircleProgressBar.dpToPx(38, this);
//        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(progressSize, progressSize);
//        layoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
//        layoutParams.setMargins(progressMargin, progressMargin, progressMargin, progressMargin);
//        progressBar.setLayoutParams(layoutParams);
//        progressBar.setRoundProgressColor(ContextCompat.getColor(this, R.color.chat_green));
//        progressBar.setRoundColor(Color.WHITE);
//        progressBar.setTextColor(Color.WHITE);
//        progressBar.setDisplayText(true);
//        progressBar.setStyle(CircleProgressBar.STROKE);
//        progressBar.setTextSize(CircleProgressBar.spToPx(12, this));
//        progressBar.setRoundWidth(CircleProgressBar.dpToPx(3, this));
//        progressBar.setUnit("%");
//
//        ZoomImageView zoomImageView = new ZoomImageView(this);
//        zoomImageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//        zoomImageView.setScaleType(ImageView.ScaleType.MATRIX);
//
//        zoomImageView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
//
//        }
//
//        frameLayout.addView(zoomImageView);
//        frameLayout.addView(progressBar);
//        progressBar.setVisibility(View.VISIBLE);
//        Threader.run(() -> {
//            for (int i = 1; i <= 100; i++) {
//                Threader.sleep(1000);
//                final int p = i;
//                runOnUiThread(() -> {
//                    progressBar.setProgress(p);
//                });
//            }
//        });
//        return frameLayout;
    }

    public void refreshItemView(ViewHolder holder, ChatTableBean chat) {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<ChatTableBean>() {
            @Override
            public void onAction(ChatTableBean item) {
                CircleProgressBar progressBar = holder.progressBar;
                ZoomImageView zoomImageView = holder.zoomImageView;
                zoomImageView.setOnClickListener(v -> finish());
                AlbumTableBean al = null;
                if (!TextUtils.isEmpty(item.getAlbumId())) {
                    al = AlbumTableBean.queryById(Long.valueOf(item.getAlbumId()));
                }
                if (al != null && !TextUtils.isEmpty(al.getMPath())) {
                    progressBar.setVisibility(View.INVISIBLE);
                    final String path = al.getMPath();
                    GlideUtil.getInstance().load(path, zoomImageView);
                } else {
                    if (!TextUtils.isEmpty(item.getFileUrl())) {
                        if (!loadMap.containsKey(item.getId())) {
                            if (Canstants.SINGLE_CHAT == item.getFromType()) {
                                progressBar.setVisibility(View.VISIBLE);
                                AlbumManageUtil.getInstance().downLoadFileFriend(item.getFileUrl(), AlbumTableBean.TYPE_IMAGE, item.getTargetId(), new AlbumManageUtil.OnFileResponse() {
                                    @Override
                                    public void onProgress(int progress) {
                                        super.onProgress(progress);
                                        progressBar.setProgress(progress);
                                        if (progress == 100) {
                                            progressBar.setVisibility(View.INVISIBLE);
                                        }
                                    }

                                    @Override
                                    public void onResult(String url, String fileId) {
                                        resultFile(fileId, item, zoomImageView);
                                        progressBar.setVisibility(View.INVISIBLE);
                                    }
                                });
                            } else {
                                progressBar.setVisibility(View.VISIBLE);
                                AlbumManageUtil.getInstance().downLoadFileGroupMember(item.getFileUrl(), AlbumTableBean.TYPE_IMAGE
                                        , item.getGroupType(), item.getGroupId(), item.getTargetType(), item.getTargetId(), new AlbumManageUtil.OnFileResponse() {

                                            @Override
                                            public void onProgress(int progress) {
                                                super.onProgress(progress);
                                                progressBar.setProgress(progress);
                                            }

                                            @Override
                                            public void onResult(String url, String fileId) {
                                                resultFile(fileId, item, zoomImageView);
                                                progressBar.setVisibility(View.INVISIBLE);
                                            }
                                        });
                            }
                        }
                        loadMap.put(item.getId(), true);

                    } else {
                        progressBar.setVisibility(View.INVISIBLE);
                    }
                }
            }

            @Override
            public ChatTableBean onThreadAction() {
                ChatTableBean item = ChatTableBean.getTableFromId(String.valueOf(chat.getId()));
                if (item != null)
                    return item;
                return chat;
            }
        });
    }

    private void resultFile(String fileId, ChatTableBean item, ZoomImageView zoomImageView) {
        if (!TextUtils.isEmpty(fileId) && Long.parseLong(fileId) > 0) {
            AlbumTableBean al = AlbumTableBean.queryById(Long.parseLong(fileId));
//            ChatTableBean chat = ChatTableBean.getTableFromId(String.valueOf(item.getId()));
//            chat.setAlbumId(fileId);
            item.setAlbumId(String.valueOf(al.getId()));
            ChatTableBean.update(item);

            if (al != null) {
                if (!TextUtils.isEmpty(al.getMPath())) {
                    GlideUtil.getInstance().load(al.getMPath(), zoomImageView);
                } else {
                    zoomImageView.setImageBitmap(BitmapFactory.decodeFile(item.getThumbPath()));
                }

//                zoomImageView.setImageBitmap(BitmapFactory.decodeFile(al.getMPath()));
            }
        }
    }

    public void setData(int count) {
        List<View> datas = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            datas.add(getZoomImageView(i));
        }
        adapter.setDatas(datas);

    }

    class ViewAdapter extends PagerAdapter {
        private List<View> datas = new ArrayList<>();

        public List<View> getDatas() {
            return datas;
        }

        public ViewAdapter() {
        }

        public void setDatas(List<View> datas) {
            this.datas = datas;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = datas.get(position);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            try {
//                ViewHolder holder = new ViewHolder(datas.get(position));
//                holder.zoomImageView.setDrawingCacheEnabled(true);
//                Bitmap bitmap = Bitmap.createBitmap(holder.zoomImageView.getDrawingCache());
//                holder.zoomImageView.setDrawingCacheEnabled(false);
//                bitmap.recycle();
//                holder.zoomImageView.setImageBitmap(null);
                container.removeView((View) object);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


//    public static void jumpTo(Context context, String targetId, String selectedId) {
//        Intent intent = new Intent(context, MulPhotoPreviewActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        intent.putExtra(Canstants.KEY_CHAT_TARGET_ID, targetId);
//        intent.putExtra(Canstants.KEY_CHAT_TARGET_SELECTED_ID, selectedId);
//        context.startActivity(intent);
//    }

    public static void jumpTo(Context context, List<ChatTableBean> list, String selectedId) {
        Intent intent = new Intent(context, MulPhotoPreviewActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Canstants.KEY_CHAT_LIST, (Serializable) list);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_SELECTED_ID, selectedId);
        context.startActivity(intent);
    }

    private synchronized void getChatList(List<ChatTableBean> list) {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<List<ChatTableBean>>() {
            @Override
            public void onAction(List<ChatTableBean> obj) {
                if (obj == null || obj.isEmpty()) {
                    return;
                }
                picList.clear();
                for (ChatTableBean bean : obj) {
                    if (!TextUtils.isEmpty(bean.getThumbPath())) {
                        picList.add(bean);
                    }
                }
                if (!picList.isEmpty()) {
                    setData(picList.size());
//                    horizontalAdapter.setList(picList);
                    for (int i = 0; i < picList.size(); i++) {
                        ChatTableBean bean = picList.get(i);
                        if (String.valueOf(bean.getId()).equals(targetSelectedId)) {
                            viewPager.setCurrentItem(i, false);
//                            recyclerView.scrollToPosition(i);
                            return;
                        }
                    }
                }


            }

            @Override
            public List<ChatTableBean> onThreadAction() {
//                List<ChatTableBean> list = ChatTableBean.queryPhotos(targetId);
                return list;
            }
        });
    }

    static class ViewHolder {
        @BindView(R.id.zoom)
        ZoomImageView zoomImageView;
        @BindView(R.id.progress)
        CircleProgressBar progressBar;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
